package com.umeox.moto.watch.themes.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;

import androidx.core.view.MarginLayoutParamsCompat;
import androidx.core.view.ViewCompat;

import com.umeox.moto.watch.themes.R;
import com.umeox.moto.watch.themes.util.MetricsUtils;


public class ActionBar extends FrameLayout {

    private ImageView mIconView;
    private int mIconRes;
    private int mIconWidth, mIconHeight;

    private TextView mTitleTextView, mSubtitleTextView;
    private LayoutParams titleTextPara, subTitleTextPara;

    private CharSequence mTitleText;
    private CharSequence mSubtitleText;

    private int mTitleTextAppearance;
    private int mSubtitleTextAppearance;

    private int mTotalLength;
    private int mDrawablePadding;
    private int mGravity;

    public ActionBar(Context context) {
        this(context, null, R.attr.u_actionBarStyle);
    }

    public ActionBar(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.u_actionBarStyle);
    }

    public ActionBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super.init(context, attrs, defStyleAttr, defStyleRes);

        final TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ActionBar, defStyleAttr, R.style.Widget_Uwear_ActionBar);

        mTitleTextAppearance = a.getResourceId(R.styleable.ActionBar_titleTextAppearance, R.style.TextAppearance_Uwear_Action);
        mSubtitleTextAppearance = a.getResourceId(R.styleable.ActionBar_subtitleTextAppearance, R.style.TextAppearance_Uwear_Desc);
        mGravity=a.getInt(R.styleable.ActionBar_gravity,1);

        mIconView = new ImageView(context);
        mIconView.setId(android.R.id.icon);
        mIconView.setImageResource(mIconRes);
        mIconView.setScaleType(ImageView.ScaleType.FIT_CENTER);


        mTitleTextView = new TextView(context);
        mIconView.setId(android.R.id.title);
        mTitleTextView.setText(mTitleText);
        mTitleTextView.setMaxLines(2);
        mTitleTextView.setGravity(Gravity.START | Gravity.CENTER_VERTICAL);
        setTitleAppearance(mTitleTextAppearance);
        mTitleTextView.setPadding(0, 0, 0, 0);
        mTitleTextView.setVisibility(TextUtils.isEmpty(mTitleText) ? GONE : VISIBLE);

        titleTextPara = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        titleTextPara.setMarginStart(mDrawablePadding);

        mSubtitleTextView = new TextView(context);
        mIconView.setId(android.R.id.hint);
        mSubtitleTextView.setText(mSubtitleText);
        mSubtitleTextView.setSingleLine(true);
        mSubtitleTextView.setGravity(Gravity.START | Gravity.CENTER_VERTICAL);
        setSubtitleAppearance(mSubtitleTextAppearance);
        mSubtitleTextView.setPadding(0, 0, 0, 0);
        mSubtitleTextView.setVisibility(TextUtils.isEmpty(mSubtitleText) ? GONE : VISIBLE);

        subTitleTextPara = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        subTitleTextPara.setMarginStart(mDrawablePadding);

        addView(mIconView, new LayoutParams(mIconWidth > 0 ? mIconWidth : LayoutParams.WRAP_CONTENT, mIconHeight > 0 ? mIconHeight : LayoutParams.WRAP_CONTENT));
        addView(mTitleTextView, titleTextPara);
        addView(mSubtitleTextView, subTitleTextPara);
    }

    @Override
    protected void applyStyle(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super.applyStyle(context, attrs, defStyleAttr, defStyleRes);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ActionBar, defStyleAttr, defStyleRes);

        for (int i = 0, count = a.getIndexCount(); i < count; i++) {
            int attr = a.getIndex(i);
            if (attr == R.styleable.ActionBar_iconRes) {
                mIconRes = a.getResourceId(attr, 0);
            } else if (attr == R.styleable.ActionBar_iconWidth) {
                final int width = a.getDimensionPixelSize(attr, 0);
                if (width > 0) {
                    mIconWidth = width;
                }
            } else if (attr == R.styleable.ActionBar_iconHeight) {
                final int height = a.getDimensionPixelSize(attr, 0);
                if (height > 0) {
                    mIconHeight = height;
                }
            } else if (attr == R.styleable.ActionBar_titleString) {
                mTitleText = a.getText(attr);
            } else if (attr == R.styleable.ActionBar_subtitleString) {
                mSubtitleText = a.getText(attr);
            } else if (attr == R.styleable.ActionBar_titleTextAppearance) {
                mTitleTextAppearance = a.getResourceId(attr, 0);
            } else if (attr == R.styleable.ActionBar_subtitleTextAppearance) {
                mSubtitleTextAppearance = a.getResourceId(attr, 0);
            } else if (attr == R.styleable.ActionBar_drawablePadding) {
                final int marginStart = a.getDimensionPixelSize(attr, (int) MetricsUtils.convertDpToPixel(context, 4));
                if (marginStart > 0) {
                    mDrawablePadding = marginStart;
                }
            }
        }
        a.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = 0;
        int height = 0;
        int childState = 0;

        int iconWidth = 0;
        if (shouldLayout(mIconView)) {
            measureChildConstrained(mIconView, widthMeasureSpec, width, heightMeasureSpec, 0, -1);
            iconWidth = mIconView.getMeasuredWidth() + getHorizontalMargins(mIconView);
            height = Math.max(height, mIconView.getMeasuredHeight() + getVerticalMargins(mIconView));
            childState = View.combineMeasuredStates(childState, mIconView.getMeasuredState());
        }
        width += iconWidth;

        int textWidth = 0;
        int textHeight = 0;
        if (shouldLayout(mTitleTextView)) {
            measureChildConstrained(mTitleTextView, widthMeasureSpec, width, heightMeasureSpec, 0, -1);
            textWidth = Math.max(textWidth, mTitleTextView.getMeasuredWidth() + getHorizontalMargins(mTitleTextView));
            textHeight += mTitleTextView.getMeasuredHeight() + getVerticalMargins(mTitleTextView);
            childState = View.combineMeasuredStates(childState, mTitleTextView.getMeasuredState());
        }

        if (shouldLayout(mSubtitleTextView)) {
            measureChildConstrained(mSubtitleTextView, widthMeasureSpec, width, heightMeasureSpec, 0, -1);
            textWidth = Math.max(textWidth, mSubtitleTextView.getMeasuredWidth() + getHorizontalMargins(mSubtitleTextView));
            textHeight += mSubtitleTextView.getMeasuredHeight() + getVerticalMargins(mSubtitleTextView);
            childState = View.combineMeasuredStates(childState, mSubtitleTextView.getMeasuredState());
        }
        width += textWidth;
        mTotalLength = width;
        height = Math.max(height, textHeight);

        width += getPaddingLeft() + getPaddingRight();
        height += getPaddingTop() + getPaddingBottom();

        final int measuredWidth = View.resolveSizeAndState(
                Math.max(width, getSuggestedMinimumWidth()),
                widthMeasureSpec, childState & View.MEASURED_STATE_MASK);
        final int measuredHeight = View.resolveSizeAndState(
                Math.max(height, getSuggestedMinimumHeight()),
                heightMeasureSpec, childState << View.MEASURED_HEIGHT_STATE_SHIFT);

        setMeasuredDimension(measuredWidth, measuredHeight);
    }

    private boolean shouldLayout(View view) {
        return view != null && view.getParent() == this && view.getVisibility() != GONE;
    }

    private int getHorizontalMargins(View v) {
        final MarginLayoutParams mlp = (MarginLayoutParams) v.getLayoutParams();
        return MarginLayoutParamsCompat.getMarginStart(mlp) +
                MarginLayoutParamsCompat.getMarginEnd(mlp);
    }

    private int getVerticalMargins(View v) {
        final MarginLayoutParams mlp = (MarginLayoutParams) v.getLayoutParams();
        return mlp.topMargin + mlp.bottomMargin;
    }

    private void measureChildConstrained(View child, int parentWidthSpec, int widthUsed,
                                         int parentHeightSpec, int heightUsed, int heightConstraint) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        int childWidthSpec = getChildMeasureSpec(parentWidthSpec,
                getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);
        int childHeightSpec = getChildMeasureSpec(parentHeightSpec,
                getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin
                        + heightUsed, lp.height);

        final int childHeightMode = MeasureSpec.getMode(childHeightSpec);
        if (childHeightMode != MeasureSpec.EXACTLY && heightConstraint >= 0) {
            final int size = childHeightMode != MeasureSpec.UNSPECIFIED ?
                    Math.min(MeasureSpec.getSize(childHeightSpec), heightConstraint) :
                    heightConstraint;
            childHeightSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
        }
        child.measure(childWidthSpec, childHeightSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final boolean isRtl = ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL;
        final int width = getWidth();
        final int height = getHeight();

        final int paddingLeft = getPaddingStart();
        final int paddingRight = getPaddingEnd();
        final int paddingTop = getPaddingTop();
        final int paddingBottom = getPaddingBottom();

        final boolean iconView = shouldLayout(mIconView);
        final boolean layoutTitle = shouldLayout(mTitleTextView);
        final boolean layoutSubtitle = shouldLayout(mSubtitleTextView);

        int right = width - paddingRight;
        //TODO
        int left;
        if(mGravity == 0){
            left = paddingLeft;
        }else{
            left = (right - paddingLeft - mTotalLength) / 2;
        }
        left = left <= paddingLeft ? paddingLeft : left;
        if (iconView) {
            if (isRtl) {
                right = layoutChildRight(mIconView, right);
            } else {
                left = layoutChildLeft(mIconView, left);
            }
        }

        int titleHeight = 0;
        if (layoutTitle) {
            final LayoutParams lp = (LayoutParams) mTitleTextView.getLayoutParams();
            titleHeight += lp.topMargin + mTitleTextView.getMeasuredHeight() + lp.bottomMargin;
        }
        if (layoutSubtitle) {
            final LayoutParams lp = (LayoutParams) mSubtitleTextView.getLayoutParams();
            titleHeight += lp.topMargin + mSubtitleTextView.getMeasuredHeight() + lp.bottomMargin;
        }

        if (layoutTitle || layoutSubtitle) {
            int titleTop;

            final View topChild = layoutTitle ? mTitleTextView : mSubtitleTextView;
            final View bottomChild = layoutSubtitle ? mSubtitleTextView : mTitleTextView;
            final LayoutParams toplp = (LayoutParams) topChild.getLayoutParams();
            final LayoutParams bottomlp = (LayoutParams) bottomChild.getLayoutParams();

            final int space = height - paddingTop - paddingBottom;
            int spaceAbove = (space - titleHeight) / 2;

            if (spaceAbove < toplp.topMargin) {
                spaceAbove = toplp.topMargin;
            } else {
                final int spaceBelow = height - paddingBottom - titleHeight -
                        spaceAbove - paddingTop;
                if (spaceBelow < toplp.bottomMargin) {
                    spaceAbove = Math.max(0, spaceAbove - (bottomlp.bottomMargin - spaceBelow));
                }
            }
            titleTop = paddingTop + spaceAbove;

            if (isRtl) {
                right -= mDrawablePadding;
                int titleRight = right;
                int subtitleRight = right;

                if (layoutTitle) {
                    final LayoutParams lp = (LayoutParams) mTitleTextView.getLayoutParams();
                    final int titleLeft = titleRight - mTitleTextView.getMeasuredWidth();
                    final int titleBottom = titleTop + mTitleTextView.getMeasuredHeight();
                    mTitleTextView.layout(titleLeft, titleTop, titleRight, titleBottom);
                    titleTop = titleBottom + lp.bottomMargin;
                }
                if (layoutSubtitle) {
                    final LayoutParams lp = (LayoutParams) mSubtitleTextView.getLayoutParams();
                    titleTop += lp.topMargin;
                    final int subtitleLeft = subtitleRight - mSubtitleTextView.getMeasuredWidth();
                    final int subtitleBottom = titleTop + mSubtitleTextView.getMeasuredHeight();
                    mSubtitleTextView.layout(subtitleLeft, titleTop, subtitleRight, subtitleBottom);
                }
            } else {
                left += mDrawablePadding;
                int titleLeft = left;
                int subtitleLeft = left;

                if (layoutTitle) {
                    final LayoutParams lp = (LayoutParams) mTitleTextView.getLayoutParams();
                    final int titleRight = titleLeft + mTitleTextView.getMeasuredWidth();
                    final int titleBottom = titleTop + mTitleTextView.getMeasuredHeight();
                    mTitleTextView.layout(titleLeft, titleTop, titleRight, titleBottom);
                    titleTop = titleBottom + lp.bottomMargin;
                }
                if (layoutSubtitle) {
                    final LayoutParams lp = (LayoutParams) mSubtitleTextView.getLayoutParams();
                    titleTop += lp.topMargin;
                    final int subtitleRight = subtitleLeft + mSubtitleTextView.getMeasuredWidth();
                    final int subtitleBottom = titleTop + mSubtitleTextView.getMeasuredHeight();
                    mSubtitleTextView.layout(subtitleLeft, titleTop, subtitleRight, subtitleBottom);
                }
            }
        }
    }

    private int layoutChildLeft(View child, int left) {
        final LayoutParams lp = (LayoutParams) child.getLayoutParams();
        left += lp.leftMargin;
        final int top = getChildTop(child);
        final int childWidth = child.getMeasuredWidth();
        child.layout(left, top, left + childWidth, top + child.getMeasuredHeight());
        left += childWidth + lp.rightMargin;
        return left;
    }

    private int layoutChildRight(View child, int right) {
        final LayoutParams lp = (LayoutParams) child.getLayoutParams();
        right -= lp.rightMargin;
        final int top = getChildTop(child);
        final int childWidth = child.getMeasuredWidth();
        child.layout(right - childWidth, top, right, top + child.getMeasuredHeight());
        right -= childWidth + lp.leftMargin;
        return right;
    }

    private int getChildTop(View child) {
        final LayoutParams lp = (LayoutParams) child.getLayoutParams();
        final int childHeight = child.getMeasuredHeight();
        final int paddingTop = getPaddingTop();
        final int paddingBottom = getPaddingBottom();
        final int height = getHeight();
        final int space = height - paddingTop - paddingBottom;
        int spaceAbove = (space - childHeight) / 2;
        if (spaceAbove < lp.topMargin) {
            spaceAbove = lp.topMargin;
        } else {
            final int spaceBelow = height - paddingBottom - childHeight -
                    spaceAbove - paddingTop;
            if (spaceBelow < lp.bottomMargin) {
                spaceAbove = Math.max(0, spaceAbove - (lp.bottomMargin - spaceBelow));
            }
        }
        return paddingTop + spaceAbove;
    }

    public int getIconWidth() {
        return mIconWidth > 0 ? mIconWidth : ViewGroup.LayoutParams.WRAP_CONTENT;
    }

    public void setIconWidth(int iconWidth) {
        mIconWidth = iconWidth;
        LayoutParams layoutParams = (LayoutParams) mIconView.getLayoutParams();
        layoutParams.width = mIconWidth > 0 ? mIconWidth : LayoutParams.WRAP_CONTENT;
        mIconView.setLayoutParams(layoutParams);
    }

    public int getIconHeigth() {
        return mIconHeight > 0 ? mIconHeight : ViewGroup.LayoutParams.WRAP_CONTENT;
    }

    public void setTitleAppearance(int resId) {
        if (resId != 0) {
            mTitleTextView.setTextAppearance(getContext(), resId);
        }
    }

    public void setSubtitleAppearance(int resId) {
        if (resId != 0) {
            mSubtitleTextView.setTextAppearance(getContext(), resId);
        }
    }

    public void setIconRes(int resId) {
        if (resId == 0) {
            mIconView.setVisibility(GONE);
        } else {
            mIconView.setVisibility(VISIBLE);
            mIconView.setImageResource(resId);
        }
    }

    public void setIconDrawable(Drawable drawable) {
        if (drawable == null) {
            mIconView.setVisibility(GONE);
        } else {
            mIconView.setVisibility(VISIBLE);
            mIconView.setImageDrawable(drawable);
        }
    }

    public void setIconHeight(int iconHeight) {
        mIconHeight = iconHeight;
        LayoutParams layoutParams = (LayoutParams) mIconView.getLayoutParams();
        layoutParams.height = mIconHeight > 0 ? mIconHeight : LayoutParams.WRAP_CONTENT;
        mIconView.setLayoutParams(layoutParams);
    }

    public void setDrawablePadding(int padding) {
        if (padding == 0) {
            return;
        }
        if (mTitleTextView.getVisibility() == VISIBLE) {
            titleTextPara.setMarginStart(padding);
            mTitleTextView.setLayoutParams(titleTextPara);
        }
        if (mSubtitleTextView.getVisibility() == VISIBLE) {
            subTitleTextPara.setMarginStart(padding);
            mSubtitleTextView.setLayoutParams(subTitleTextPara);
        }
    }

    public void setTitleText(CharSequence text) {
        if (TextUtils.isEmpty(text)) {
            mTitleTextView.setVisibility(View.INVISIBLE);
        } else {
            mTitleTextView.setVisibility(View.VISIBLE);
            mTitleTextView.setText(text);
        }
    }

    public void setTitleText(int id) {
        if (id == 0) {
            setTitleText(null);
        } else {
            setTitleText(getContext().getResources().getString(id));
        }
    }

    public void setSubtitleText(CharSequence text) {
        if (TextUtils.isEmpty(text)) {
            mSubtitleTextView.setVisibility(View.INVISIBLE);
        } else {
            mSubtitleTextView.setVisibility(View.VISIBLE);
            mSubtitleTextView.setText(text);
        }
    }

    public void setSubtitleText(int id) {
        if (id == 0) {
            setSubtitleText(null);
        }
        setSubtitleText(getContext().getResources().getString(id));
    }
}
